package com.dmooo.ymx.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dmooo.ymx.R;
import com.dmooo.ymx.adapter.ShopRecyclerAdapter2;
import com.dmooo.ymx.base.BaseActivity;
import com.dmooo.ymx.bean.HaoDanBean;
import com.dmooo.ymx.bean.Response;
import com.dmooo.ymx.bean.SearchHistoryBean;
import com.dmooo.ymx.bean.TaobaoGuestBean;
import com.dmooo.ymx.common.ACache;
import com.dmooo.ymx.config.Constants;
import com.dmooo.ymx.https.HttpUtils;
import com.dmooo.ymx.https.onOKJsonHttpResponseHandler;
import com.dmooo.ymx.mall.MallGoodsDetailsActivity;
import com.dmooo.ymx.malladapter.ShopMallGoodsRecyclerAdapter;
import com.dmooo.ymx.malladapter.ShopMallGridAdapter;
import com.dmooo.ymx.mallbean.MallCatbean;
import com.dmooo.ymx.mallbean.ShopMallGoodsBean;
import com.dmooo.ymx.utils.StringUtils;
import com.dmooo.ymx.utils.UIUtils;
import com.dmooo.ymx.widget.AutoClearEditText;
import com.dmooo.ymx.widget.NoScrollGridView;
import com.dmooo.ymx.widget.indicator.buildins.UIUtil;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.wrapper.HeaderAndFooterWrapper;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cz.msebera.android.httpclient.Header;

/**
 * 搜索结果
 * Created by yohn on 2018/8/25.
 */

public class ShopMallSearchResultActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.bg_head)
    LinearLayout bg_head;
    @BindView(R.id.tv_title)
    AutoClearEditText tvTitle;
    @BindView(R.id.tv_left)
    TextView tv_left;
    @BindView(R.id.tv_right)
    TextView tvRight;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    Unbinder unbinder;
    private String min_id = "", tb_p = "";

    @BindView(R.id.right_icon)
    ImageView rightIcon;

    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    private int indexNum = 1;
    private int status = 0;

    private ShopMallGoodsRecyclerAdapter shopRecyclerAdapter;
    private NoScrollGridView gridView;
    private String pid;

//    List<MallCatbean> subListByParentChildBeans = new ArrayList<>();
    List<ShopMallGoodsBean> taobaoGuesChildtBeans = new ArrayList<>();
    private ShopMallGridAdapter shopGridAdapter;

    //界面传值 关键字 券后区间价开始 结束 分享比例开始值 结束值
    String content, stMoney, enMoney, shareOne, shareTwo;//
    int tmall = -1, type;//type 1 高级搜素 0 普通搜索

    private String sort = "0";
    private HeaderAndFooterWrapper headerAndFooterWrapper;
    private boolean hasdata=true;


//    List<TaobaoGuestBean.TaobaoGuesChildtBean> taobaoGuesChildtBeans = new ArrayList<>();
    List<SearchHistoryBean> historyBeans = new ArrayList<>();
//    private ShopRecyclerAdapter2 shopRecyclerAdapter;
    private LinearLayoutManager linearLayoutManager;
//    private ShopHighRecyclerAdapter shopHighRecyclerAdapter;



    Boolean isPricaeDes = true;
    private ACache aCache;

    @Override
    protected void initUI() {
        setContentView(R.layout.activity_shopsearch_result);
        unbinder = ButterKnife.bind(this);
        aCache = ACache.get(getComeActivity());
    }

    @Override
    protected void initData() {
        tv_left.setVisibility(View.VISIBLE);
        tvTitle.setTextColor(getResources().getColor(R.color.col_333));
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            if (bundle.containsKey("content")) {
                content = bundle.getString("content");
            }
            //来源
            if (bundle.containsKey("type")) {
                type = bundle.getInt("type");
            }
        }
        tvTitle.setText(content);
        tvTitle.setBackground(getResources().getDrawable(R.drawable.bg_round_gray));
        //管理器
        linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        //适配器
//        if (type == 0) {
//        shopRecyclerAdapter = new ShopRecyclerAdapter2(this, R.layout.today_highlights_child_item, taobaoGuesChildtBeans);
//        recyclerView.setAdapter(shopRecyclerAdapter);


        gridView = new NoScrollGridView(ShopMallSearchResultActivity.this);
        gridView.setNumColumns(4);
        gridView.setGravity(Gravity.CENTER);
        gridView.setBackgroundColor(getResources().getColor(R.color.white));
        RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(0, 0, 0, UIUtil.dip2px(ShopMallSearchResultActivity.this, 5));
        layoutParams.width = RecyclerView.LayoutParams.MATCH_PARENT;
        layoutParams.height = RecyclerView.LayoutParams.WRAP_CONTENT;

        gridView.setLayoutParams(layoutParams);
//        shopGridAdapter = new ShopMallGridAdapter(ShopMallSearchResultActivity.this, R.layout.service_home_grid_item, subListByParentChildBeans);
//        gridView.setAdapter(shopGridAdapter);
        shopRecyclerAdapter = new ShopMallGoodsRecyclerAdapter(ShopMallSearchResultActivity.this, R.layout.shop_mall_goods_item, taobaoGuesChildtBeans);
        recyclerView.setLayoutManager(new GridLayoutManager(ShopMallSearchResultActivity.this,2));
        headerAndFooterWrapper = new HeaderAndFooterWrapper(shopRecyclerAdapter);
        headerAndFooterWrapper.addHeaderView(gridView);
        recyclerView.setAdapter(headerAndFooterWrapper);


        //显示回滚
//        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                super.onScrolled(recyclerView, dx, dy);
//                //屏幕高度
//                int screenMeasuredHeight = UIUtils.getScreenMeasuredHeight(ShopMallSearchResultActivity.this);
//                //如果滚动距离大于屏幕高度，那么显示回滚，否则。。。
//                if (getScollYDistance() >= (screenMeasuredHeight / 2)) {
//                    rightIcon.setVisibility(View.VISIBLE);
//                } else {
//                    rightIcon.setVisibility(View.GONE);
//                }
//                Log.d("TAG", "高度为:" + getScollYDistance());
//
//            }
//        });

        //开始刷新
        refreshLayout.autoRefresh();
    }

    @Override
    protected void initListener() {
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                status = 0;
                if (hasdata) {
                    indexNum++;
                    getTbkListRequst(content);
                } else {
                    showToast("没有更多数据了");
                    refreshLayout.finishLoadMore(2000);
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                status = 1;
                hasdata=true;
                indexNum=1;
                getTbkListRequst(content);
            }
        });
        tv_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        List<SearchHistoryBean> searchHistoryBeans = (List<SearchHistoryBean>) aCache.getAsObject(Constants.HISTORICAL_RECORDS);
        if (searchHistoryBeans != null && searchHistoryBeans.size() > 0) {
            historyBeans.addAll(searchHistoryBeans);
        }

        tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(StringUtils.doViewToString(tvTitle))) {
                    ((InputMethodManager) tvTitle.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(
                                    getComeActivity()
                                            .getCurrentFocus()
                                            .getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
                    //存储历史
                    SearchHistoryBean searchHistoryBean = new SearchHistoryBean();
                    searchHistoryBean.setContent(StringUtils.doViewToString(tvTitle));
                    if (!historyBeans.contains(searchHistoryBean)) {
                        historyBeans.add(searchHistoryBean);
                        aCache.put(Constants.HISTORICAL_RECORDS, (Serializable) historyBeans);
                    }
                    content = tvTitle.getText().toString().trim();
                    refreshLayout.autoRefresh();
                } else {
                    showToast("你未输入搜索内容");
                }
            }
        });
        tvTitle.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (!TextUtils.isEmpty(StringUtils.doViewToString(tvTitle))) {
                    ((InputMethodManager) tvTitle.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(
                                    getComeActivity()
                                            .getCurrentFocus()
                                            .getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
                    //存储历史
                    SearchHistoryBean searchHistoryBean = new SearchHistoryBean();
                    searchHistoryBean.setContent(StringUtils.doViewToString(tvTitle));
                    if (!historyBeans.contains(searchHistoryBean)) {
                        historyBeans.add(searchHistoryBean);
                        aCache.put(Constants.HISTORICAL_RECORDS, (Serializable) historyBeans);
                    }
                    content = tvTitle.getText().toString().trim();
                    refreshLayout.autoRefresh();
                } else {
                    showToast("你未输入搜索内容");
                }
                return false;
            }
        });

        //点击进入详情
        shopRecyclerAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                ShopMallGoodsBean taobaoGuesChildtBean = taobaoGuesChildtBeans.get(position-1);
                if (taobaoGuesChildtBean != null) {
                    Bundle bundle = new Bundle();
                    bundle.putString("goods_id", taobaoGuesChildtBean.goods_id);
                    openActivity(MallGoodsDetailsActivity.class, bundle);
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    @OnClick({R.id.right_icon})
    public void onViewClicked(View view) { //回到头部
        switch (view.getId()) {
            case R.id.right_icon:
                recyclerView.post(new Runnable() {
                    @Override
                    public void run() {
                        recyclerView.smoothScrollToPosition(0);
                    }
                });
                break;

        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
        }
    }


    /**
     * @属性:获取淘宝客商品列表
     * @开发者:陈飞
     * @时间:2018/7/26 17:05
     */
    private void getTbkListRequst(String search) {
        if (TextUtils.isEmpty(search)) {
            if (refreshLayout != null) {
                if (status == 1) {
                    refreshLayout.finishRefresh();
                } else {
                    refreshLayout.finishLoadMore();
                }
            }
            showToast("未传查询词");
            return;
        }
        RequestParams requestParams = new RequestParams();
        requestParams.put("p", indexNum);
        requestParams.put("goods_name", search);
        requestParams.put("per", 10);
        HttpUtils.post(Constants.APP_IP+"/app.php?c=Goods&a=getGoodsList", requestParams, new onOKJsonHttpResponseHandler<ShopMallGoodsBean>(new TypeToken<Response<ShopMallGoodsBean>>() {
        }) {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                showToast(responseString);
            }

            @Override
            public void onSuccess(int statusCode, Response<ShopMallGoodsBean> datas) {
                if (datas.isSuccess()) {
                    List<ShopMallGoodsBean> list = datas.getData().list;
                    if (status == 1) {
                        taobaoGuesChildtBeans.clear();
                    }
                    taobaoGuesChildtBeans.addAll(list);
                    if(list.size()<=0){
                        hasdata=false;
                    }
                } else {
                    showToast(datas.getMsg());
                }
                headerAndFooterWrapper.notifyDataSetChanged();
                if (refreshLayout != null) {
                    if (status == 1) {
                        refreshLayout.finishRefresh();
                    } else {
                        refreshLayout.finishLoadMore();
                    }
                }
            }
        });
    }


    /**
     * @属性:获取屏幕高度的方法
     * @开发者:陈飞
     * @时间:2018/8/7 14:22
     */
    public int getScollYDistance() {
        int position = linearLayoutManager.findFirstVisibleItemPosition();
        View firstVisiableChildView = linearLayoutManager.findViewByPosition(position);
        int itemHeight = firstVisiableChildView.getHeight();
        return (position) * itemHeight - firstVisiableChildView.getTop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }
}
